﻿/*
 * Created by SharpDevelop.
 * User: Alice
 * Date: 04.03.2012
 * Time: 20:12
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.IO;
using System.Text;
using System.Timers;
using System.Diagnostics;

namespace FreewarClone
{
	/// <summary>
	/// Description of Logger.
	/// </summary>
	public class Logger2
	{
		private StreamWriter sw;
		private Configuration c;
		public DateTime lastLog;
		
		public String DEBUG;
		public String ERROR;
		public String WARNING;
		public String INFO;
		public int CONSOLE;
		public int BOTH;
		public int LOGFILE;
		public int dayOfMonth;
		
		public Logger2(Configuration c)
		{			
			this.c = c;
			this.dayOfMonth = 0;
			this.lastLog = DateTime.Now;
			
			//this.sw = File.AppendText(@"logs\logs.txt");
			this.sw = null;
			this.DEBUG = "DEBUG";
			this.ERROR = "ERROR";
			this.WARNING = "WARNING";
			this.INFO = "INFO";
			this.CONSOLE = 1;
			this.BOTH = 2;
			this.LOGFILE = 3;
			
		}
		
		public String getFileName()
		{
			return @DateTime.Now.Year + "-" + DateTime.Now.Month.ToString("00") + "-" + DateTime.Now.Day.ToString("00") + ".txt";
		}
		
		public StreamWriter getStream()
		{
			if(DateTime.Now.Day != this.dayOfMonth)
			{
				if(this.sw != null)
					this.sw.Close();
				this.sw = File.AppendText(this.c.logDir + this.getFileName());
			}
		
			return this.sw;
		}
		
		public void writeServerAliveToLog(object sender, ElapsedEventArgs e)
		{
			if((this.lastLog.AddMinutes(this.c.serverAliveKeepOutTime)).CompareTo(DateTime.Now) <= 0)
			{
				this.writeInfo(this.BOTH,"Server Alive!");
			}
		}
		
		public void writeError(int type, String text)
		{
			this.log(type, this.ERROR, text);
		}
		
		public void writeError(int type, Error e)
		{
			this.writeError(type, e.toString());
		}
		
		public void writeInfo(int type, String text)
		{
			this.log(type, this.INFO, text);
		}
		
		public void writeDebug(int type, String text)
		{
			if(this.c.debugMode)
				this.log(type, this.DEBUG, text);
		}
		
		public void writeWarning(int type, String text)
		{
			this.log(type, this.WARNING, text);
		}
		
		public void log(int mode, String type, String text)
		{
			this.lastLog = DateTime.Now;
			String toWrite = this.lastLog.ToString("HH:mm:ss - ");
			toWrite += type + " - ";
			toWrite += text;
			
			if(mode == this.CONSOLE || mode == this.BOTH)
			{
				// Nur Konsole
				Console.WriteLine(toWrite);
				
				if(mode == this.BOTH)
				{
					this.getStream().WriteLine(toWrite);
					this.getStream().Flush();
				}
			}
			if(mode == this.LOGFILE)
			{
				this.getStream().WriteLine(toWrite);
				this.getStream().Flush();
			}
		}
	}
}
